﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.Weather.Entities;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace DispatchAssist.Weather.Helper
{
    class WeatherDataHelper
    {
        private static WeatherData weatherData;
        public static WeatherData WeatherData
        {
            get
            {
                return weatherData ?? (weatherData = GetData());
            }
        }

        private static string GetFileName()
        {
            return string.Format("{0}data.wd", AppDomain.CurrentDomain.BaseDirectory);
        }

        public static void SaveData(WeatherData data)
        {
            try
            {
                using (FileStream fs = new FileStream(GetFileName(), FileMode.Create))
                {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fs, data);
                }
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error(ex);
            }
        }

        private static WeatherData GetData()
        {
            WeatherData data;
            try
            {
                using (FileStream fs = new FileStream(GetFileName(), FileMode.OpenOrCreate))
                {
                    IFormatter formatter = new BinaryFormatter();
                    data = (WeatherData)formatter.Deserialize(fs);

                    
                }
            }
            catch (Exception ex)
            {
                data = new WeatherData();
                CarolLib.Log.Instance.Error(ex);
            }
            return data;
        }

    }
}
